import store from '@/store/index.js';
import Setting from '../setting.js'
import {uploadCosApi} from '@/api/home.js'

// 从本地或拍照获取图片路径
const uploadLocation = (count, module, collBack)=> {
	uni.chooseImage({
	    count: count, // 默认9
	    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
	    sourceType: ['album', 'camera'], // 从相册选择
	    success: (res)=> {
			upLoadServe(res.tempFilePaths, module, (urlList)=> {
				collBack(urlList)
				uni.showToast({
					title: '上传成功'
				})
			})
	    }
	});
}

// 上传图片 | 文件到服务器
const upLoadServe = (list, module, callBack)=> {
	let imgList = []
	let index = 1
	const load = async (step) => {
		if(!step) {step = 0;}
		if(step > list.length - 1) {
			callBack(imgList)
			uni.hideLoading();
			return ;
		}
		uni.showLoading({
			title: `正在上传`,
		})
		if(list[step].uploaded){
			load(step+1); 
			return ;
		}
		const i = list[step].lastIndexOf('.')
		// const name = (step+1) + list[step].substring(i, list[step].length);
		const name = new Date().getTime() + list[step].substring(i, list[step].length);
		try{
			const COSAuth = await uploadCosApi({ filetmp: name, file_module: 'signature' })
			COSAuth.data = {
				'OSSAccessKeyId': COSAuth.datas.OSSAccessKeyId,
				'policy': COSAuth.datas.policy,
				'Signature': COSAuth.datas.Signature,
				'key': COSAuth.datas.key,
				'success_action_status': COSAuth.datas.success_action_status,
			}
			// console.log('COSAuth', COSAuth);
			uni.uploadFile({
				url      : COSAuth.datas.url,
				filePath : list[step],
				name     : 'file',
				formData : COSAuth.data,
				// header   : { 'token': store.state.login.token },
				success  : (res) => {
					if (res.statusCode === COSAuth.datas.success_action_status) {
						imgList[step] = { url: '', val: {},  uploaded: false}
						imgList[step].url = COSAuth.datas.val.src
						imgList[step].val = COSAuth.datas.val
						imgList[step].uploaded = true
					} else {
						uni.showToast({
							icon: 'none',
							title: '图片上传失败'
						})
					}
					index = index+1
					load(step+1); 
				},
				fail: (err) => {
					console.log('错误err:', err)
					uni.hideLoading()
					uni.showToast({
						mask: true,
						icon: 'none',
						title: err.errMsg
					})
				}
			});
		}catch(e){
			//TODO handle the exception
		}		
	}
	load()
}

const previewImage = (list, index) => {
	uni.previewImage({
		current: index,
		urls: list,
		longPressActions: {
			itemList: ['发送给朋友', '保存图片', '收藏'],
			success: function(data) {
			},
			fail: function(err) {
			}
		}
	});
}

module.exports = {
	uploadLocation,
	upLoadServe,
	previewImage
}